package com.example.bills;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.bills.MultiChoiceDialog.OnSelectedVisibleListener;
import com.example.finalapp.R;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseUser;

public class Edit_new_billActivity extends Activity implements OnSelectedVisibleListener
{
	CharSequence[] mRoom8Name;
	boolean[] mCheckedItemsArray;
	MultiChoiceDialog newDialog;
	Bundle args;
	EditText link;
	boolean incorrectUrlFlag;
	EditText visibleToText;
	EditText titleText;
	EditText createdBy;
	int selectedSize;


	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_new_bill);

		incorrectUrlFlag = false;
		newDialog = new MultiChoiceDialog();
		args 	  = new Bundle();

		Button nextButton   = (Button)findViewById(R.id.btnNext);
		Button doneButton   = (Button)findViewById(R.id.btnDone);
		link 	    		= (EditText)findViewById(R.id.link_for_payment);
		visibleToText 		= (EditText)findViewById(R.id.visible_to_names);
		titleText 	  		= (EditText)findViewById(R.id.editTitle);
		createdBy              = (EditText)findViewById(R.id.edit_create);

		createdBy.setText(ParseUser.getCurrentUser().get("Name").toString());
		getRoommateListFromServer();
		/*Handling VisibleTO field*/
		visibleToText.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) 
			{
				if(mRoom8Name == null)//waiting for query to retrieve all users in apartment
				{
					getRoommateListFromServer();
				}
				newDialog.setArguments(args);
				newDialog.show(getFragmentManager(), "newDialog");
			}
		});
		/*Handling Clicking Next Button*/
		nextButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) 
			{
				String url = link.getText().toString();
				String title = visibleToText.getText().toString();
				String visibleTo = titleText.getText().toString();
				
				if(!url.matches(""))/*checks if there is an input from the user*/
				{	
					if(!Patterns.WEB_URL.matcher(url).matches())/* Checks if URL is valid*/
					{		
						//link.setText("");
						//link.setHintTextColor(getResources().getColor(R.color.red));
						Toast.makeText(Edit_new_billActivity.this,getResources().getString(R.string.url_error),Toast.LENGTH_LONG).show();
						incorrectUrlFlag = true;
					}
					else
					{	/*Vaild url*/
						incorrectUrlFlag = false;
					}
				}
				else
				{		/*user left an empty link field.*/
					incorrectUrlFlag = false;
				}

				if(incorrectUrlFlag == false)
				{
					boolean result = checkEmptyFields();
					if(result == false)
					{	 /* can continue with next button*/
						Intent intent = new Intent(Edit_new_billActivity.this, Bill_InformationActivity.class);

						intent.putExtra("payment", url);
						intent.putExtra("titleKey", title);
						intent.putExtra("visibleToKey", visibleTo);
						intent.putExtra("Roommates", mRoom8Name);
						intent.putExtra("visibleToSize", selectedSize);
						startActivity(intent);
					}
				}
			}
		});
		/*Handling Clicking Done Button*/
		doneButton.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				
				boolean result = checkEmptyFields();
				
				if(result == false)
				{
					String url = link.getText().toString();
					String title = visibleToText.getText().toString();
					String visibleTo = titleText.getText().toString();
					
					Intent intent = new Intent(Edit_new_billActivity.this, BillsActivity.class);
					intent.putExtra("urlKey", url);
					intent.putExtra("titleKey", title);
					intent.putExtra("visibleToKey", visibleTo);
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.edit_new_bill, menu);
		return true;
	}

	@Override
	public void onCancelSelected(boolean isAdminDialog) 
	{

	}
	public boolean checkEmptyFields()
	{
		boolean missingVisibleFieldFlag = false;
		boolean missingTitleFieldFlag   = false;
		
		String visibleField = visibleToText.getText().toString();
		String titleField = titleText.getText().toString();

		if(visibleField.matches(""))
		{
			Edit_new_billActivity.this.visibleToText.setError(getResources().getString(R.string.missingVisibleTo));
			missingVisibleFieldFlag = true;
		}
		if(titleField.matches(""))
		{
			Edit_new_billActivity.this.titleText.setError(getResources().getString(R.string.missingTitle));
			missingTitleFieldFlag = true;
		}
		if(missingTitleFieldFlag == false && missingVisibleFieldFlag == false)
		{		/*Fields are OK */
			return false;
		}
		else
		{		/*Missing fields!!!!!!!*/
			return true;
		}
	}
	public void getRoommateListFromServer()
	{
		ParseQuery<ParseUser> query = ParseUser.getQuery();
		query.whereEqualTo("Apartment", ParseUser.getCurrentUser().get("Apartment"));
		query.whereEqualTo("isConfirmed", true);
		query.findInBackground(new FindCallback<ParseUser>() {
			public void done(List<ParseUser> objects, ParseException e) 
			{
				int room8NameIndex;
				int sizeOfReturnedTable;

				if (e == null) 
				{
					sizeOfReturnedTable = objects.size();
					mRoom8Name = new String[sizeOfReturnedTable];
					mCheckedItemsArray = new boolean[mRoom8Name.length];

					for(room8NameIndex = 0; room8NameIndex < sizeOfReturnedTable ; room8NameIndex++)
					{
						mRoom8Name[room8NameIndex] = (CharSequence) objects.get(room8NameIndex).get("Name");
					}

					args.putCharSequenceArray(MultiChoiceDialog.ARG_STRING_ID, mRoom8Name);
					args.putBooleanArray(MultiChoiceDialog.Bool_Array_ID, mCheckedItemsArray);
				} 
				else 
				{
					// Something went wrong.
				}
			}
		});

	}
	@Override
	public void onConfirmSelected(ArrayList<String> aStringArray,boolean[] aCheckedItemsArray) 
	{
		int aStringArrayIndex; 
		int sizeOfaStringArray;

		sizeOfaStringArray = aStringArray.size();

		for(int checkItemsIndex=0;checkItemsIndex < mCheckedItemsArray.length;checkItemsIndex++)
		{
			mCheckedItemsArray[checkItemsIndex] = aCheckedItemsArray[checkItemsIndex];
		}
		StringBuilder tempString = new StringBuilder();

		for(aStringArrayIndex = 0; aStringArrayIndex < sizeOfaStringArray;aStringArrayIndex++)
		{

			if(aStringArrayIndex == sizeOfaStringArray-1)
			{
				tempString.append(aStringArray.get(aStringArrayIndex));
			}
			else
			{
				tempString.append(aStringArray.get(aStringArrayIndex)+",");
			}


			visibleToText.setText(tempString.toString());
		}
		if(sizeOfaStringArray == 0)
		{
			visibleToText.setText("");
		}

		selectedSize = sizeOfaStringArray;	/* amount of room mates chosen, passes over to bill Information */
	}




}
